package com.controllers;

import com.daos.ClientDao;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.models.Client;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;

@Controller
public class ClientController {

  @Autowired
  private ClientDao clientDao;

  @Value("${com.admin.name}")
  private String mongoAdminUser;

  @Value("${com.admin.password}")
  private String mongoAdminPass;

  @Value("${com.admin.email}")
  private String mongoAdminEmail;

  private final ObjectMapper mapper = new ObjectMapper();

  public Client getClient(String username) {
    return clientDao.getClient(username);
  }

  public Client saveClient(String request) throws IOException {
    Client publisher = createClient(request);
    return publisher;
  }

  public Client createAdmin() {
    String encryptedPassword = Client.encryptPassword(mongoAdminPass);
    Client admin = clientDao.getClient(mongoAdminUser);

    if (admin == null) {
      admin = new Client();
      admin.setUserName(mongoAdminUser);
    }

    admin.setPassword(encryptedPassword);
    admin.setEmail(mongoAdminEmail);
    admin.setRole(1);
    clientDao.saveClient(admin);

    return admin;

  }

  private Client createClient(String data) throws IOException {
    Client client = mapper.readValue(data, Client.class);
    String encryptedPassword = Client.encryptPassword(client.getPassword());
    client.setPassword(encryptedPassword);
    client.setRole(2);
    clientDao.saveClient(client);
    return client;
  }

}
